package com.hundsun.yr.universal.p2p.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.data.HSSharedPreferences;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Config;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseMineWebActivity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.Log;
import com.umeng.socialize.utils.ShareBoardlistener;

import java.lang.ref.WeakReference;

import de.greenrobot.event.EventBus;

public class WebNewsShareActivity extends BaseMineWebActivity implements OnClickListener {
    /**
     * 支持放大缩小
     */
    public static final String supportZoom = "supportZoom";
    private boolean supportZoomFlag;

    private ShareAction mShareAction;

    private UMShareListener mShareListener;
    /**
     * 用户SharedPreferences
     **/
    public HSSharedPreferences sharedPreferences = null;
    private String title;
    private String content;
    private final int LOGIN = 1;


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        if (mBrowserLayout == null) {
        }
        return mBrowserLayout;
    }


    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        mBrowserLayout.refresh();
        toggleHide();

    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        supportZoomFlag = extras.getBoolean(supportZoom);
    }

    @Override
    protected void onNetworkDisConnected() {

        toggleNetworkError(true, new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (NetUtils.isNetworkConnected(getBaseContext())) {
                    showToast("请检查网络...");
                } else {
                    mBrowserLayout.refresh();
                    toggleHide();
                }
            }
        });

    }

    @Override
    protected void initViewsAndEvents() {
        sharedPreferences = new HSSharedPreferences(mContext, Config.SPPath.file_userLoginedInfo);
        setCookie();
        super.initViewsAndEvents();
//        toolbar_title.setText(mWebTitle);
        toolbar_menu.setBackgroundResource(R.drawable.share_icon);
        mToolBar.setNavigationOnClickListener(this);

        toolbar_menu.setOnClickListener(this);
        toolbar_menu.setVisibility(View.GONE);

        mShareListener = new CustomShareListener(WebNewsShareActivity.this);

        mShareAction = new ShareAction(WebNewsShareActivity.this).setDisplayList(
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE,
                SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE)
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        UMWeb web = new UMWeb(mWebUrl);
                        if (title == null || title.isEmpty()) {
                            web.setTitle("【中网国投】");
                        } else {
                            web.setTitle(title);
                        }

                        if (content == null || content.isEmpty()) {
                            web.setDescription("立即注册即可领取5元现金券，首次出借后还送20元，你还等什么？");
                        } else {
                            web.setDescription(content);
                        }

                        web.setThumb(new UMImage(WebNewsShareActivity.this, R.drawable.icon));
                        new ShareAction(WebNewsShareActivity.this).withMedia(web)
                                .setPlatform(share_media)
                                .setCallback(mShareListener)
                                .share();
//                        }
                    }
                });

        WebChromeClient wvcc = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
//                Logs.e("ReceivedTitle: " + title);
                toolbar_title.setMaxLines(1);
                toolbar_title.setMaxEms(7);
                toolbar_title.setEllipsize(TextUtils.TruncateAt.END);
                if (title != null && !title.isEmpty()) {
                    toolbar_title.setText(title);
                }
            }
        };
        mBrowserLayout.getWebView().setWebChromeClient(wvcc);

        mBrowserLayout.getWebView().getSettings().setJavaScriptEnabled(true);
        mBrowserLayout.getWebView().addJavascriptInterface(WebNewsShareActivity.this, "java_obj");
        mBrowserLayout.getWebView().addJavascriptInterface(WebNewsShareActivity.this, "java_title");
        mBrowserLayout.getWebView().addJavascriptInterface(WebNewsShareActivity.this, "wjj");
        mBrowserLayout.getWebView().setWebViewClient(new CustomWebViewClient());

        if (supportZoomFlag) {
            mBrowserLayout.mWebView.getSettings().setSupportZoom(supportZoomFlag);
            mBrowserLayout.mWebView.getSettings().setBuiltInZoomControls(supportZoomFlag);
        }
    }

    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * 网页 返回
     */
    public void webBack() {
        if (mBrowserLayout.canGoBack()) {
            mBrowserLayout.goBack();
        } else {
            finish();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            webBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_menu:
                checkPermissions();
                break;
            default:
                webBack();
                break;
        }
    }

    private void checkPermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            String[] mPermissionList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            };
            ActivityCompat.requestPermissions(this, mPermissionList, 123);
        }
    }

    private static class CustomShareListener implements UMShareListener {

        private WeakReference<MainActivity> mActivity;

        private CustomShareListener(Activity activity) {
            mActivity = new WeakReference(activity);
        }

        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(mActivity.get(), platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                        && platform != SHARE_MEDIA.EMAIL
                        && platform != SHARE_MEDIA.FLICKR
                        && platform != SHARE_MEDIA.FOURSQUARE
                        && platform != SHARE_MEDIA.TUMBLR
                        && platform != SHARE_MEDIA.POCKET
                        && platform != SHARE_MEDIA.PINTEREST

                        && platform != SHARE_MEDIA.INSTAGRAM
                        && platform != SHARE_MEDIA.GOOGLEPLUS
                        && platform != SHARE_MEDIA.YNOTE
                        && platform != SHARE_MEDIA.EVERNOTE) {
                    Toast.makeText(mActivity.get(), platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                }

            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (platform != SHARE_MEDIA.MORE && platform != SHARE_MEDIA.SMS
                    && platform != SHARE_MEDIA.EMAIL
                    && platform != SHARE_MEDIA.FLICKR
                    && platform != SHARE_MEDIA.FOURSQUARE
                    && platform != SHARE_MEDIA.TUMBLR
                    && platform != SHARE_MEDIA.POCKET
                    && platform != SHARE_MEDIA.PINTEREST

                    && platform != SHARE_MEDIA.INSTAGRAM
                    && platform != SHARE_MEDIA.GOOGLEPLUS
                    && platform != SHARE_MEDIA.YNOTE
                    && platform != SHARE_MEDIA.EVERNOTE) {
                Toast.makeText(mActivity.get(), platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
                if (t != null) {
                    Log.d("throw", "throw:" + t.getMessage());
                }
            }

        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {

            Toast.makeText(mActivity.get(), platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    }

    final class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            mWebUrl = url;
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:window.java_obj.getContent(document.querySelector('.news-content').innerText);");
            view.loadUrl("javascript:window.java_title.getTitle(document.querySelector('.news-title').innerText);");
            super.onPageFinished(view, url);
            if (!url.contains("newslist")) {
                toolbar_menu.setVisibility(View.VISIBLE);
            } else {
                toolbar_menu.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
    }

    @JavascriptInterface
    public void getContent(String content) {
        this.content = content;
    }

    @JavascriptInterface
    public void getTitle(String title) {
        this.title = title;
    }

    @JavascriptInterface
    public void investList() {
        EventBus.getDefault().post(new EventCenter(Extras.RECHARGE_SUCCESS_GO_TO_PROJECT));
        finish();
    }

    @JavascriptInterface
    public void login() {
        Bundle bundle = new Bundle();
        bundle.putString("WHERE", "WebNewsShareActivity");
        readyGoForResult(LoginActivity.class, LOGIN, bundle);
    }

    private void setCookie() {
        syncCookie(mContext, mWebUrl, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case LOGIN:
                setCookie();
                refresh();
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        if (requestCode == 123) {
            mShareAction.open();
        }
    }
}
